#include "index.hpp"
#include "util.hpp"
#include <algorithm>
#include <iterator>
#include <unordered_map>
#include <jsoncpp/json/json.h>

namespace ns_searcher
{
    // 解决去重问题的结点
    struct InvertedElemPrint
    {
        uint64_t doc_id;
        std::vector<std::string> words;
        int weight;
        InvertedElemPrint():doc_id(0), weight(0){}
    };

    class Searcher
    {
    public:
        Searcher(){}
        ~Searcher(){}
        void InitSearcher(const std::string &input)
        {
            // 1. 获取或者创建index对象
            _index = ns_index::Index::GetInstance();
            // 2. 根据index对象建⽴索引
            _index->BuildIndex(input);
        }
        //query: 搜索关键字
        //json_string: 返回给用户浏览器的搜索结果
        void Search(const std::string &query, std::string *json_string)
        {
            // 1.[分词]:对我们的query进行按照searcher的要求进行分词
            std::vector<std::string> words;
            ns_util::JiebaUtil::CutString(query, &words);
            // 2.[触发]:就是根据分词的各个"词"，进行index查找
            // ns_index::InvertedList inverted_list_all;
            std::vector<InvertedElemPrint> inverted_list_all;  // 去重
            std::unordered_map<uint64_t, InvertedElemPrint> tokens_map;

            for(std::string word : words)
            {
                boost::to_lower(word);

                ns_index::InvertedList *inverted_list = _index->GetInvertedList(word);  // 倒排查找
                if(inverted_list == nullptr)
                {
                    continue;
                }
                // inverted_list_all.insert(inverted_list_all.end(), inverted_list->begin(), inverted_list->end());
                // 解决去重问题
                for(const auto &elem : *inverted_list)
                {
                    auto &item = tokens_map[elem.doc_id];
                    item.doc_id = elem.doc_id;
                    item.weight += elem.weight;
                    item.words.push_back(elem.word);
                }
                for(const auto &item : tokens_map)
                {
                    inverted_list_all.push_back(std::move(item.second));
                }
            }
            // 3.[合并排序]：汇总查找结果，按照相关性(weight)降序排序
            // std::sort(inverted_list_all.begin(), inverted_list_all.end(), \
            //     [](const ns_index::InvertedElem &e1, const ns_index::InvertedElem &e2){
            //         return e1.weight > e2.weight;
            //     });
            // 解决去重
            std::sort(inverted_list_all.begin(), inverted_list_all.end(), \
                [](const InvertedElemPrint &e1, const InvertedElemPrint &e2){
                    return e1.weight > e2.weight;
                });

            // 4.[构建]:根据查找出来的结果，构建json串 -- jsoncpp
            Json::Value root;
            for(auto &item : inverted_list_all)
            {
                ns_index::DocInfo *doc = _index->GetForwardIndex(item.doc_id);  //正排查找
                if(doc == nullptr)
                    continue;
                Json::Value elem;
                elem["title"] = doc->title;
                // elem["desc"] = GetDesc(doc->content, item.word);
                elem["desc"] = GetDesc(doc->content, item.words[0]);  // 去重
                elem["url"] = doc->url;

                root.append(elem);
            }
            //Json::StyledWriter writer;
            Json::FastWriter writer;
            *json_string = writer.write(root);
        }
    private:
        // 截取描述
        std::string GetDesc(const std::string &html_content, const std::string &word)  
        {
            const int prev_step = 50;
            const int next_step = 100;
            // 1.找到word首次在html_content出现的位置，不能使用find直接查找，这样会有大小写的问题
            auto iter = std::search(html_content.begin(), html_content.end(), word.begin(), word.end(), \
                [](int x, int y){
                    return (std::tolower(x) == std::tolower(y));   
                });
            if(iter == html_content.end())
            {
                return "None";
            }
            // 获取两个迭代器之间的距离
            int pos = std::distance(html_content.begin(), iter);
            // 2.获取start，end
            int start = 0;
            int end = html_content.size() - 1;
            // 3.更新start，end的值
            if(pos - prev_step > start) start = pos - prev_step;
            if(pos + next_step < end)   end = pos + next_step;
            // 4. 截取字串
            if(start >= end)    return "None";
            std::string desc = html_content.substr(start, end - start);
            desc += "...";
            return desc;
        }
    private:
        ns_index::Index *_index; //供系统进行查找的索引
    };
}